package org.fanrui.hrm.controller;

import io.minio.errors.*;
import org.fanrui.hrm.exception.GlobalException;
import org.fanrui.hrm.util.AjaxResult;
import org.fanrui.hrm.util.MinioUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 文件上传下载
 *
 * @author fanrui
 */
@RestController
public class FileController {
    @Resource
    private MinioUtil minioUtil;

    @PostMapping("/upload")
    public AjaxResult upload(@RequestBody MultipartFile file) {
        try {
            String fileName = minioUtil.uploadFile(file);
            return AjaxResult.me().setSuccess(true).setMessage("上传成功").setResultObj(fileName);
        } catch (GlobalException | IOException | ServerException | InsufficientDataException | InternalException |
                 InvalidResponseException | InvalidKeyException | NoSuchAlgorithmException | ErrorResponseException |
                 XmlParserException e) {
            return AjaxResult.me().setSuccess(false).setMessage("上传失败").setResultObj(null);
        }
    }

    @GetMapping("/download")
    public AjaxResult download() {
        try {
            return AjaxResult.me().setSuccess(true).setMessage("下载成功").setResultObj(null);
        } catch (GlobalException e) {
            return AjaxResult.me().setSuccess(false).setMessage("下载失败").setResultObj(null);
        }
    }

    @DeleteMapping("/delete")
    public AjaxResult delete() {
        try {
            return AjaxResult.me().setSuccess(true).setMessage("删除成功").setResultObj(null);
        } catch (GlobalException e) {
            return AjaxResult.me().setSuccess(false).setMessage("删除失败").setResultObj(null);
        }
    }
}
